package org.icnmasjid.member.webapp.action;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.icnmasjid.member.webapp.action.BaseFormController;
import org.icnmasjid.member.model.MemberInformation;
import org.icnmasjid.member.model.Person;
import org.icnmasjid.member.model.PersonPayment;
import org.icnmasjid.member.model.PersonSubOrgRole;
import org.icnmasjid.member.model.Role;
import org.icnmasjid.member.model.SubOrg;
import org.icnmasjid.member.service.PersonManager;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import com.sun.mail.iap.Response;

public class PersonFormController extends BasePersonFormController {
    public void setPersonManager(PersonManager personManager) {
        this.personManager = personManager;
    }
    public PersonFormController() {
        setCommandName("person");
        setCommandClass(Person.class);
    }

    protected Object formBackingObject(HttpServletRequest request)
    throws Exception {
        String personId = request.getParameter("personId");
        Person person = null;

        if (!StringUtils.isEmpty(personId)) {
            person = personManager.getPerson(personId);
        } else {
            person = new Person();
        }

        return person;
    }

    @Override
    protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors) throws Exception {
    	super.onBindAndValidate(request, command, errors);
    	Person p = (Person)command;
    	// bind the memberships manually
    	Iterator<MemberInformation> i = p.getMemberInformations().iterator();
    	while ( i.hasNext() ) {
    		if ( !p.getMemberYear().contains(i.next().getYearOfMembership()) ) {
    			i.remove();
    		}
    	}
    	for ( int year: p.getMemberYear() ) {
    		p.setMember(true, year);
    	}
    }

    public ModelAndView onSubmit(HttpServletRequest request,
                                 HttpServletResponse response, Object command,
                                 BindException errors)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("entering 'onSubmit' method...");
        }

        Person person = (Person) command;
        boolean isNew = (person.getPersonId() == null);
        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
            personManager.removePerson(person.getPersonId().toString());

            saveMessage(request, getText("person.deleted", locale));
        } else if ("addRole".equals(request.getParameter("action"))) {
        	return addRole(request, response, person);
        } else if ("deleteRole".equals(request.getParameter("action"))) {
        	return deleteRole(request, response, person);
        } else if ("addPayment".equals(request.getParameter("action"))) {
        	return addPayment(request, response, person);
        } else if ("deletePayment".equals(request.getParameter("action"))) {
        	return deletePayment(request, response, person);
        } else {
        	person.setPrimaryPerson(Boolean.TRUE);
            personManager.savePerson(person);

            String key = (isNew) ? "person.added" : "person.updated";
            saveMessage(request, getText(key, locale));

            if (!isNew) {
                return new ModelAndView("redirect:editPerson.html", "personId", person.getPersonId());
            }
        }

        return new ModelAndView(getSuccessView());
    }
	private ModelAndView deletePayment(HttpServletRequest request, HttpServletResponse response, Person person) {
		String id = request.getParameter("personPaymentId");
		PersonPayment pp = (PersonPayment)getManager().getObject(PersonPayment.class, Integer.valueOf(id));
		person.getPersonPayments().remove(pp);
		personManager.savePerson(person);
		Map map = new HashMap();
		map.put("person", person);
		map.put("personPayments", person.getPersonPayments());
		map.put("personPaymentsList", person.getPersonPaymentsList());
		return new ModelAndView("ajax_personPayment", map);
	}
	private ModelAndView addPayment(HttpServletRequest request, HttpServletResponse response, Person person) {
		// get the payment params
		PersonPayment pp = person.getPersonPayment();
		pp.setPerson(person);
		person.getPersonPayments().add(pp);
		personManager.savePerson(person);
		Map map = new HashMap();
		map.put("person", person);
		map.put("personPayments", person.getPersonPayments());
		map.put("personPaymentsList", person.getPersonPaymentsList());
		return new ModelAndView("ajax_personPayment", map);

	}
	
	private ModelAndView sendPaymentReceipt(HttpServletRequest request, HttpServletResponse response, Person person) {
		// send an email to parents for a given payment category
		
		Map map = new HashMap();		
		return new ModelAndView("ajax_personPayment", map);
	}
}
